package com.TeacherInfoServer.common.service.Impl;

import com.TeacherInfoServer.pojo.DTO.DepartmentDTO;
import com.TeacherInfoServer.pojo.DTO.SearchDTO.DepartmentSearchDTO;
import com.TeacherInfoServer.pojo.entity.Department;
import com.TeacherInfoServer.pojo.entity.Teacher;
import com.TeacherInfoServer.exception.RecordExistDetailException;
import com.TeacherInfoServer.exception.TeacherNameNotExistException;
import com.TeacherInfoServer.mapper.DepartmentMapper;
import com.TeacherInfoServer.common.service.CommentService;
import com.TeacherInfoServer.common.service.DepartmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 教研室服务实现类
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {
    @Autowired
    public DepartmentMapper departmentMapper;

    @Autowired
    public CommentService commentService;

    @Override
    public Map<String, Object> getDepartmentList(Integer pages, Integer size){
        Page<DepartmentDTO> page = new Page<>(pages, size);
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        Page<DepartmentDTO> resultPage = departmentMapper.getDepartmentListByPage(page,queryWrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("totals",resultPage.getTotal());
        data.put("currentPages",resultPage.getCurrent());
        data.put("pageNumber",resultPage.getPages());
        data.put("rows",resultPage.getRecords());
        return data;
    }
    @Override
    public List<DepartmentDTO> getDepartmentDTOS(){
       return departmentMapper.selectDepartmentWithLeadersAndDirectors();
    }

    @Override
    public Map<String,Object> searchDepartmentList(DepartmentSearchDTO departmentSearchDTO){
        Page<DepartmentDTO> page = new Page<>(departmentSearchDTO.getPages(), departmentSearchDTO.getSize());
        departmentMapper.searchDepartmentList(page,departmentSearchDTO);
        Map<String, Object> data = new HashMap<>();
        data.put("totals",page.getTotal());
        data.put("currentPages",page.getCurrent());
        data.put("pageNumber",page.getPages());
        data.put("rows",page.getRecords());
        return data;
    }
    @Transactional
    @Override
    public void addDepartment(String name, String leaderName, String directorName){
        QueryWrapper<Department> queryWrapper =new QueryWrapper<>();
        if(departmentMapper.selectOne(queryWrapper.eq("name",name))== null) {
            Department department = new Department();
            Teacher leader = commentService.findTeacherByName(leaderName);
            if (leader == null) {
                throw new TeacherNameNotExistException("未找到专业负责人");
            }
            Teacher director = commentService.findTeacherByName(directorName);
            if (director == null) {
                throw new TeacherNameNotExistException("未找到教研室主任");
            }
            department.setName(name);
            department.setLeaderId(leader.getTeacherId());
            department.setDirectorId(director.getTeacherId());
            departmentMapper.insert(department);

        }else {
            throw new RecordExistDetailException("教研室已存在");
        }
    }
    @Transactional
    @Override
    public void addDepartmentByDTO(DepartmentDTO departmentDTO){
        Department department =new Department();
        Teacher leader = commentService.findTeacherByName(departmentDTO.getLeaderName());
        if (leader == null) {
            throw new TeacherNameNotExistException("未找到专业负责人");
        }
        Teacher director = commentService.findTeacherByName(departmentDTO.getDirectorName());
        if (director == null) {
            throw new TeacherNameNotExistException("未找到教研室主任");
        }
        department.setName(departmentDTO.getName());
        department.setLeaderId(leader.getTeacherId());
        department.setDirectorId(director.getTeacherId());
        departmentMapper.insert(department);
    }
    @Transactional
    @Override
    public void updateDepartment(DepartmentDTO departmentDTO){

            Teacher leader = commentService.findTeacherByName(departmentDTO.getLeaderName());
            if (leader == null) {
                throw new TeacherNameNotExistException("未找到专业负责人" + departmentDTO.getLeaderName());
            }
            Teacher director = commentService.findTeacherByName(departmentDTO.getDirectorName());
            if (director == null) {
                throw new TeacherNameNotExistException("未找到教研室主任" + departmentDTO.getDirectorName());
            }
            QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
            if(departmentMapper.selectOne(queryWrapper
                    .eq("id",departmentDTO.getId())
                    .eq("name",departmentDTO.getName())
                    .eq("leader_id",leader.getTeacherId())
                    .eq("director_id",director.getTeacherId())) !=null){
                throw new RecordExistDetailException("未进行更新");
        }
            UpdateWrapper<Department> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", departmentDTO.getId())
                    .set("name", departmentDTO.getName())
                    .set("leader_id", leader.getTeacherId())
                    .set("director_id", director.getTeacherId());

        departmentMapper.update(null, updateWrapper);
        QueryWrapper<Department> queryWrapper1 =new QueryWrapper<>();
        if(departmentMapper.selectList(queryWrapper1.eq("name",departmentDTO.getName())).size() >1) {
            throw new RecordExistDetailException("教研室名称已存在");
        }

    }
    @Transactional
    @Override
    public boolean deleteDepartment(List<Long> ids){
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        QueryWrapper<Department> queryWrapper= new QueryWrapper<>();
        queryWrapper.in("id",ids);
        int deleteCount=departmentMapper.delete(queryWrapper);
        return deleteCount>0;
    }
    @Override
    public Department findDepartmentByName(String name){
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        return departmentMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<String,Object> getDepartmentNameList(String departmentName){
        LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Department::getName, Department::getId);
        if(departmentName != null && !departmentName.isEmpty()) {
            queryWrapper.like(Department::getName,departmentName);
        }
        return Map.of("rows", departmentMapper.selectMaps(queryWrapper).stream()
                .map(d -> Map.of(
                        "departmentName", d.get("name"),
                        "departmentId", d.get("id")
                ))
                .collect(Collectors.toList()));
    }
}
